package com.mouliu.base.concurrent18;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author mouliu
 * @create 2018-04-15-下午10:35
 */
public class UseSemaphore {
    public static void main(String[] args){
        //线程池
        ExecutorService executorService =
                Executors.newCachedThreadPool();
        //只能5个线程同时访问
        final Semaphore semaphore =
                new Semaphore(5);
        for (int index=0;index<20;index++){
            final  int  NO = index;
            Runnable run =
                    new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //获取许可
                                semaphore.acquire();
                                System.out.println("Accessing:"+NO);
                                //模拟实际业务逻辑
                                Thread.sleep((long) (Math.random()*10000));
                                //访问完后,释放
                                semaphore.release();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    };
            executorService.execute(run);
        }
    }
}
